
const fs = require('fs');
const http = require('http');
const path = require('path');

const express = require('express');
const app = express();

const config = require('./config.js');

const staticPath = '../static/';

//静态服务器
app.use('/public', express.static(staticPath + 'dist'));

//路由 
app.get('/index.html', (req, rep) => {
	fs.readFile(staticPath + 'index.html', 'utf-8', (err, file) => {
		if(err){
			rep.send(err);
			return;
		}
		rep.send(file);
	});
});
app.get('/news/:page', (req, rep) => {
	const options = {
		hostname: config.baidu_api.host,
		port: config.baidu_api.port,
		path: config.baidu_api.news.path + '?count=10&keyword=' + encodeURI(config.baidu_api.news.keyword) + '&page=' + req.params['page'],
    method: config.baidu_api.news.method,
		headers: {
			'apikey': config.baidu_api.apikey
		}
	};
	var req2 = http.request(options, function(res) {
    res.setEncoding('utf8');   
   	var body = '';  
    res.on('data', function (data) { 
    	body += data; 
    }).on('end', function () { 
    	rep.status(200).send(body); 
		});
	});
	req2.on('error', function(e) {
	  rep.send("错误：" + e.message);
	});
	req2.end();
});
app.get('/weather/:cityname', (req, rep) => {
	var cityname = req.params['cityname'] ? req.params['cityname'] : '北京';
	const options = {
		hostname: config.baidu_api.host,
		port: config.baidu_api.port,
		path: config.baidu_api.weather.path + '?cityname=' + encodeURI(cityname),
    method: config.baidu_api.weather.method,
		headers: {
			'apikey': config.baidu_api.apikey
		}
	};
	var req2 = http.request(options, function(res) {
    res.setEncoding('utf8');   
   	var body = '';  
    res.on('data', function (data) { 
    	body += data; 
    }).on('end', function () { 
    	rep.status(200).send(body); 
		});  
	});
	req2.on('error', function(e) {
	  rep.send("错误：" + e.message);
	});
	req2.end();
});

//启动服务器
app.listen(3000, () => {
  console.log('server running at port 3000');
});